﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCoreStudy.Web.Models;

namespace DotNetCoreStudy.Web.services
{
    public class DepartmentService : IDepartmentService
    {
        public readonly List<Department> _departments = new List<Department>();

        public DepartmentService()
        {
            _departments.Add(new Department
            {
                Id = 1,
                Name = "HR",
                EmployeeCount = 16,
                Location = "Beijing"
            });
            _departments.Add(new Department
            {
                Id = 2,
                Name = "R&D",
                EmployeeCount = 52,
                Location = "Shanghai"
            });
            _departments.Add(new Department
            {
                Id = 3,
                Name = "Sales",
                EmployeeCount = 200,
                Location = "China"
            });
        }

        public Task Add(Department department)
        {
            department.Id = _departments.Max(x => x.Id) + 1;
            _departments.Add(department);
            return Task.CompletedTask;
        }

        public Task Update(Department department)
        {
            return Task.Run(function: () =>
            {
                var model = _departments.FirstOrDefault(x => x.Id == department.Id);
                if (model != null)
                {
                    model = department;
                    return model;
                }
                return null;
            });
        }

        public Task<IEnumerable<Department>> GetAll()
        {
            return Task.Run(function: () => _departments.AsEnumerable());
        }

        public Task<CompanySummary> GetCompanySummary()
        {
            return Task.Run(function: () =>
             {
                 return new CompanySummary()
                 {
                     EmployeeCount = _departments.Sum(x => x.EmployeeCount),
                     DepartmentCount = _departments.Count,
                     AverageDepartmentEmployeeCount = (int)_departments.Average(x => x.EmployeeCount)
                 };
             });
        }

        /// <summary>
        /// 根据部门id获取部门详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Task<Department> GetDepartmentById(int Id)
        {
            return Task.Run(function: () => _departments.FirstOrDefault(x => x.Id == Id));
        }
    }
}
